<?php


namespace app\admin\model;

use app\admin\service\SystemLogWithUId;
use Jackchow\Rbac\Traits\RbacUser;
use think\exception\Exception;
use think\Model;
use think\Db;
use app\api\model\StoreModel;
class Admin extends Model
{
    use SystemLogWithUId;
    use RbacUser;

    protected $prefix = 'jxc';
    protected $pk = 'id';

    public function roles()
    {
        return $this->belongsToMany(
            config('rbac.role'),
            config('rbac.role_user_table'),
            config('rbac.role_foreign_key'),
            config('rbac.user_foreign_key')
        );
    }

    public function saveData($data)
    {
        return $this::create([
            'username' => $data['username'],
            'password' => MD5($data['password']),
            'phone' => $data['username'],
            'status' => 1,
            'level' => 2,
            'create_time' => time()
        ]);
    }

    protected static function init()
    {
        // 注册用户事件
        self::afterWrite(function ($model) {
            self::log(['uid' => $model->id]);
        });
    }

    public function getAllMaker()
    {
        return self::field('id,name')->select();
    }

    public function getAllSales()
    {
        return self::field('id,name')->where('level', 3)->select();
    }

    public function Add($data)
    {
        return self::create($data);
    }

    public function Edit($id,$data)
    {
        return self::where('id',$id)->update($data);
    }

    public function getAdminInfo($id)
    {
        $list = self::find($id);
        $list['store_name'] = StoreModel::where('id',$list['store'])->value('name');
        $list['entry_time'] = date('Y-m-d',$list['entry_time']);
        return $list;
    }

    public function del($id)
    {
        $list =self::findOrFail($id);
        $arr =Db::name('sale')->where('sales',$id)->find();
        if(in_array($list['level'],[1,2])){
            throw new \Exception('系统管理员,无法删除');
        }else if($arr){
            throw new \Exception('该账号开具了单据,无法删除');
        }else{
            return self::where(['id'=>$id])->delete();
        }
    }
}
